package cn.kbyue.security.security;

import cn.kbyue.security.entity.KbUser;
import java.util.Optional;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author xlang
 * @version 0.0.1
 * @date 2021/9/14 18:51
 */
public class SecurityUtil {

    public static KbUser getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            DefinedUserDetails userDetails = (DefinedUserDetails) authentication.getPrincipal();
            return userDetails.getUser();
        }
        return null;
    }

    public static String getUserId() {
        return Optional.ofNullable(getUser())
                .map(KbUser::getUserId)
                .orElse("");
    }

}
